package com.yygo.webapp.controller;

import com.yygo.model.VehicleBrand;
import com.yygo.model.VehicleModel;
import com.yygo.model.VehicleSeries;
import com.yygo.model.enums.CarType;
import com.yygo.service.GenericManager;
import com.yygo.service.VehicleBrandManager;
import com.yygo.service.VehicleModelManager;
import com.yygo.service.VehicleSeriesManager;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

@Controller
@RequestMapping("/importvehicle*")
public class ImportVehicleController extends BaseFormController {

    private static final Log log = LogFactory.getLog(ImportVehicleController.class);

    private VehicleBrandManager vehicleBrandManager;
    private VehicleSeriesManager vehicleSeriesManager;
    private VehicleModelManager vehicleModelManager;

    @Autowired
    public void setVehicleBrandManager(VehicleBrandManager vehicleBrandManager) {
        this.vehicleBrandManager = vehicleBrandManager;
    }

    @Autowired
    public void setVehicleSeriesManager(VehicleSeriesManager vehicleSeriesManager) {
        this.vehicleSeriesManager = vehicleSeriesManager;
    }

    @Autowired
    public void setVehicleModelManager(VehicleModelManager vehicleModelManager) {
        this.vehicleModelManager = vehicleModelManager;
    }

    public ImportVehicleController() {
        setCancelView("redirect:/home");
        setSuccessView("importVehicleSuccess");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    public FileUpload showForm() {
        return new FileUpload();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(FileUpload fileUpload, BindingResult errors, HttpServletRequest request)
            throws Exception {

        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(fileUpload, errors);

            if (errors.hasErrors()) {
                return "importvehicle";
            }
        }

        // validate a file was entered
        if (fileUpload.getFile().length == 0) {
            Object[] args =
                    new Object[]{getText("uploadForm.file", request.getLocale())};
            errors.rejectValue("file", "errors.required", args, "File");

            return "importvehicle";
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

        //retrieve the file data
        InputStream stream = file.getInputStream();

        log.debug("clear up all vehicle data.");
        vehicleBrandManager.clearAll();
        int count = importVehicle(stream);
        log.debug(count + " vehicles have been imported.");
        //close the stream
        stream.close();

        // place the data into the request for retrieval on next page
        request.setAttribute("vehicleCount", count);

        return getSuccessView();
    }

   private int importVehicle(InputStream is) {
        int count = 0;
        try {
            Workbook rwb = Workbook.getWorkbook(is);
            Sheet[] sheets = rwb.getSheets();
            int importedCount = importSheet(rwb.getSheet(0), false);
            count += importedCount;
            importedCount = importSheet(rwb.getSheet(1), true);
            count += importedCount;
        }catch (Exception ex) {
            ex.printStackTrace();
        }

       return count;
    }

    private int importSheet(Sheet st, boolean imported) {
        int count = 0;
        String letter = ""; // st.getName();
        int rs=st.getColumns();
        int rows=st.getRows();

        VehicleBrand vehicleBrand = null;
        VehicleSeries vehicleSeries = null;

        String prevBrand="", prevSeries = "";

        for(int k = 1;k < rows; k++){
            String brand = st.getCell(0,k).getContents();
            String series = st.getCell(1,k).getContents();
            String model = st.getCell(2,k).getContents();
            String price = st.getCell(3,k).getContents();
            String importType = st.getCell(4,k).getContents();
            if (!model.equals("")) {
                if (!brand.equals(prevBrand)) {
                    prevBrand = brand;
                    vehicleBrand = new VehicleBrand(letter, brand);
                    vehicleBrand = vehicleBrandManager.save(vehicleBrand);
                }
                if (!series.equals(prevSeries)) {
                    prevSeries = series;
                    vehicleSeries = new VehicleSeries(series);
                    vehicleSeries.setVehicleBrand(vehicleBrand);
                    vehicleBrand.getVehicleSeries().add(vehicleSeries);
                    vehicleSeries = vehicleSeriesManager.save(vehicleSeries);
                }
                // add model
                Long guidePrice = 0L;
                try {
                    guidePrice = Long.valueOf(price);
                } catch (Exception ex) {
                    System.out.println("price is not value at row " + (k+1));
                }
                VehicleModel vehicleModel = new VehicleModel(model, guidePrice);
                vehicleModel.setVehicleSeries(vehicleSeries);
                vehicleModel.setCarType(CarType.new_and_old);
                vehicleSeries.getVehicleModels().add(vehicleModel);
                if (guidePrice > 0)
                    vehicleModel.setSecondPrice(guidePrice*80/100);

                //log.debug("importing vehicle model: " + vehicleModel.toString());
                if (imported) {
                    vehicleModel.setImported(true);
                }
                vehicleModelManager.save(vehicleModel);
                count++;

            }
        }
        return count;
    }


}
